{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import math \n",
    "import random"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def H(sentence):\n",
    "    \"\"\" Equation. 3.49 (Shannon's Entropy) is implemented \"\"\"\n",
    "    \n",
    "    entropy = 0\n",
    "    \n",
    "    # There are 256 possible ASCII characters\n",
    "    for character_i in range(256):\n",
    "        Px = sentence.count(chr(character_i))/len(sentence)\n",
    "        if Px > 0:\n",
    "            entropy += -Px * math.log(Px,2) # Note: log of base 2 (for bits)\n",
    "    return entropy\n",
    "\n",
    "# The Telegrapher creates the \"encoded message\" with length 10000\n",
    "# When he uses only 32 chars\n",
    "simple_message = \"\".join([chr(random.randint(0,32)) for i in range(10000)])\n",
    "\n",
    "# When he uses all 255 chars\n",
    "complex_message = \"\".join([chr(random.randint(0,255)) for i in range(10000)])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Message: Seeing is believing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5.041717003409252"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "H(simple_message)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "7.982184614596441"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "H(complex_message)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Takeaway:\n",
    "\n",
    "The entropy increases as the uncertainity of which characters will be sent increases."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
